from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.models.role_permission import RolePermission as RolePermissionModel, RolePermissionInDB
from app.schemas.role_permission import RolePermission as RolePermissionSchema, RolePermissionCreate, RolePermissionUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/role-permissions", tags=["角色权限管理"])

@router.post("/create", response_model=APIResponse[RolePermissionSchema])
def create_role_permission(role_permission: RolePermissionCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating role permission with role_id: {role_permission.role_id}, permission_id: {role_permission.permission_id}")
    
    # 检查角色权限关联是否已存在
    db_role_permission = db.query(RolePermissionModel).filter(
        RolePermissionModel.role_id == role_permission.role_id,
        RolePermissionModel.permission_id == role_permission.permission_id
    ).first()
    if db_role_permission:
        logger.warning(f"Role permission already registered with role_id: {role_permission.role_id}, permission_id: {role_permission.permission_id}")
        return error_response(message="Role permission already registered", code=400)
    
    # 创建新角色权限关联
    db_role_permission = RolePermissionModel(
        role_id=role_permission.role_id,
        permission_id=role_permission.permission_id,
        create_time=datetime.utcnow()
    )
    
    db.add(db_role_permission)
    db.commit()
    db.refresh(db_role_permission)
    
    # 转换为Pydantic模型
    role_permission_response = RolePermissionInDB.model_validate(db_role_permission)
    
    logger.info(f"Role permission created successfully with ID: {db_role_permission.id}")
    return success_response(data=role_permission_response, message="Role permission created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[RolePermissionSchema]])
def read_role_permissions(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching role permissions with skip: {skip}, limit: {limit}")
    
    role_permissions = db.query(RolePermissionModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    role_permissions_response = [RolePermissionInDB.model_validate(role_permission) for role_permission in role_permissions]
    total = db.query(RolePermissionModel).count()
    
    logger.info(f"Found {len(role_permissions)} role permissions")
    return paginated_response(
        items=role_permissions_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{role_permission_id}", response_model=APIResponse[RolePermissionSchema])
def read_role_permission(role_permission_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching role permission with ID: {role_permission_id}")
    
    db_role_permission = db.query(RolePermissionModel).filter(RolePermissionModel.id == role_permission_id).first()
    if db_role_permission is None:
        logger.warning(f"Role permission not found with ID: {role_permission_id}")
        return error_response(message="Role permission not found", code=404)
    
    # 转换为Pydantic模型
    role_permission_response = RolePermissionInDB.model_validate(db_role_permission)
    
    logger.info(f"Role permission found with ID: {role_permission_id}")
    return success_response(data=role_permission_response)

@router.put("/{role_permission_id}", response_model=APIResponse[RolePermissionSchema])
def update_role_permission(role_permission_id: int, role_permission: RolePermissionUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating role permission with ID: {role_permission_id}")
    
    db_role_permission = db.query(RolePermissionModel).filter(RolePermissionModel.id == role_permission_id).first()
    if db_role_permission is None:
        logger.warning(f"Role permission not found with ID: {role_permission_id}")
        return error_response(message="Role permission not found", code=404)
    
    # 更新角色权限关联信息
    update_data = role_permission.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_role_permission, key, value)
    
    db.commit()
    db.refresh(db_role_permission)
    
    # 转换为Pydantic模型
    role_permission_response = RolePermissionInDB.model_validate(db_role_permission)
    
    logger.info(f"Role permission updated successfully with ID: {role_permission_id}")
    return success_response(data=role_permission_response, message="Role permission updated successfully")

@router.delete("/{role_permission_id}", response_model=APIResponse[None])
def delete_role_permission(role_permission_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting role permission with ID: {role_permission_id}")
    
    db_role_permission = db.query(RolePermissionModel).filter(RolePermissionModel.id == role_permission_id).first()
    if db_role_permission is None:
        logger.warning(f"Role permission not found with ID: {role_permission_id}")
        return error_response(message="Role permission not found", code=404)
    
    db.delete(db_role_permission)
    db.commit()
    
    logger.info(f"Role permission deleted successfully with ID: {role_permission_id}")
    return success_response(message="Role permission deleted successfully")
